using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Sedna.Core.Controller;
using Sedna.Core.Controller.Common;
using Sedna.Core.Persistence;
using Sedna.Util;

namespace Sedna.Core.Controls.Actions
{
    public class CreateCollectionProviderAction: AbstractAction
    {
        private string providerPath;
        private string collectionPath;
        private string sortExpressionPath;
        private string isAscPath;
        private bool createEmptyIfNull;

        #region Properties

        public string ProviderPath
        {
            set { providerPath = value; }
        }

        public string CollectionPath
        {
            set { collectionPath = value; }
        }

        public string SortExpressionPath
        {
            set { sortExpressionPath = value; }
        }

        public string IsAscPath
        {
            set { isAscPath = value; }
        }

        public bool CreateEmptyIfNull
        {
            set { createEmptyIfNull = value; }
        }

        #endregion


        public override IActionResult Execute(IExecutionContext executionContext)
        {
                        
            ICollection collection = GetCollection();
            if (collection==null)
            {
                return CreateResult("collectionIsNull");
            }
            
            IDataProvider provider;
            if (sortExpressionPath!=null)
            {
                provider =
                    new CollectionProvider(collection, (string) executionContext.GetPropertyValue(sortExpressionPath),
                                           (bool) executionContext.GetPropertyValue(isAscPath));
            }
            else
            {
                provider = new CollectionProvider(collection);
            }

            executionContext.SetPropertyValue(providerPath, provider);
            return CreateResult("success");
        }

        private ICollection GetCollection()
        {
            ICollection collection = (ICollection)scopePathParser.Parse(collectionPath).Value;
            if (collection==null&&createEmptyIfNull)
            {
                return new ArrayList(0);    
            }
            return collection;
        }
    }
}
